package com.lsh.oms.core.utils;

import com.alibaba.fastjson.JSON;
import com.lsh.base.common.json.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author peter
 */
public class SMSUtils {

private static Logger log = LoggerFactory.getLogger(SMSUtils.class);
	
	public static boolean signSMS(Map<String, Object> params, String shopServiceUrl, String logSign) {
	    List<BasicNameValuePair> pairs = new ArrayList<>(2);
	    pairs.add(new BasicNameValuePair("order_id", params.get("orderCode")+""));
	    pairs.add(new BasicNameValuePair("money", params.get("money")+""));
	    pairs.add(new BasicNameValuePair("receipt_order_id", params.get("receiptOrderId")+""));
	    pairs.add(new BasicNameValuePair("receipt_at", params.get("receiptAt")+""));
	    pairs.add(new BasicNameValuePair("shipping_order_id", params.get("shippingOrderId")+""));
	    pairs.add(new BasicNameValuePair("arrived_at", params.get("arrivedAt")+""));
	    pairs.add(new BasicNameValuePair("uid", params.get("uid")+""));
	    pairs.add(new BasicNameValuePair("zone_id", params.get("zoneId")+""));
	    pairs.add(new BasicNameValuePair("address_id", params.get("addressId")+""));
	    HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
	    Header[] headers = {new BasicHeader("api-version", "1.1"),
				new BasicHeader("platform", "oms"),
				new BasicHeader("sign", "md5"),
				new BasicHeader("venderId", String.valueOf(params.get("venderId")))};
	    shopServiceUrl = shopServiceUrl + "/order/receipt/done";
	    log.info(logSign + "请求签收完成url:"+shopServiceUrl + "headers " + JSON.toJSONString(headers));
	//    log.info(logSign + "请求商品服务参数:"+JsonUtils.obj2Json(entity))
	    Map<String, Object> obj;
	    String res ;
	    try {
	    	long start = System.currentTimeMillis();
			res = HttpUtils.post(shopServiceUrl, entity, false, headers).getData();
			log.info(logSign + "请求签收完成耗时是: "+(System.currentTimeMillis() -start)+"ms");
			log.info(logSign + "请求签收完成返回结果是: "+res);
//	        JSONObject content = JSON.parseObject(res).getJSONObject("content");
	        if (res == null) {
	            log.error(logSign +"请求签收完成返回空，参数是:" + JsonUtils.obj2Json(params));
	            return false;
	        }
	        obj = JsonUtils.json2Obj(res, HashMap.class);
		} catch (Throwable e) {
			log.info(logSign + "请求签收完成返回结果转json失败");
			return false;
		}
	    if(!obj.get("ret").equals(0) || StringUtils.isEmpty(obj.get("content")+"")){
	    		log.info(logSign + "请求签收完成返回结果失败");
	    		return false;
	    }

	    return true;
	}

}
